package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.constant.CartListConstant;
import com.dongdongshop.constant.IdWorker;
import com.dongdongshop.constant.PayConstant;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.service.SellerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@org.springframework.stereotype.Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private TbOrderMapper tbOrderMapper;

    @Resource
    private TbOrderItemMapper tbOrderItemMapper;

    @Reference
    private SellerService sellerService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional
    public Map<String,Object> insertOrder(TbOrder tbOrder, TbAddress tbAddress, List<Cart> carts) {
        IdWorker idWorker = new IdWorker();
        //母订单号
        Long parentOrderId = idWorker.nextId();
        //购物车总价
        double moneySum = 0;
        for (Cart cart : carts) {
            long id = idWorker.nextId();
            tbOrder.setOrderId(id);//创建新订单
            tbOrder.setStatus("1");//为付款
            tbOrder.setCreateTime(new Date());
            tbOrder.setUpdateTime(new Date());
            tbOrder.setReceiverAreaName(tbAddress.getProvince() + tbAddress.getCity() + tbAddress.getTown() + tbAddress.getAddress());//地址
            tbOrder.setReceiverMobile(tbAddress.getMobile());
            tbOrder.setReceiver(tbAddress.getContact());
            tbOrder.setSourceType("2");
            tbOrder.setSellerId(cart.getSellerId());
            tbOrder.setPayOrderId(parentOrderId.toString());

            //循环购物车明细
            double money = 0;
            for (TbOrderItem tbOrderItem : cart.getTbOrderItemList()) {
                tbOrderItem.setId(idWorker.nextId());
                tbOrderItem.setOrderId(tbOrder.getOrderId());//订单id
                tbOrderItem.setSellerId(cart.getSellerId());
                money += tbOrderItem.getTotalFee().doubleValue();
                tbOrderItemMapper.insertSelective(tbOrderItem);
            }
            moneySum += money;
            tbOrder.setPayment(new BigDecimal(money));
            tbOrderMapper.insertSelective(tbOrder);
        }

        redisTemplate.expire(CartListConstant.CAR_LIST_KEY,5,TimeUnit.SECONDS);

        // 将购物车信息放入母订单号对应的redis中
        redisTemplate.boundHashOps(PayConstant.PAY_KEY + tbOrder.getUserId()).put(parentOrderId.toString(), carts);
        redisTemplate.boundHashOps(PayConstant.PAY_KEY + tbOrder.getUserId()).expire(1, TimeUnit.HOURS);

        Map<String,Object> map = new HashMap<>();
        map.put("out_trade_no",parentOrderId.toString());
        map.put("total_amount",moneySum);
        map.put("subject","支付商品");
        map.put("body","hhhhh");
        return map;
    }

    @Override
    public Object getOrdersByParenOrderId(String out_trade_no) {
        TbOrderExample toe = new TbOrderExample();
        TbOrderExample.Criteria criteria = toe.createCriteria();
        criteria.andPayOrderIdEqualTo(out_trade_no);
        return tbOrderMapper.selectByExample(toe);
    }

    @Override
    public int updateOrderStatus(List<TbOrder> orderList) {
        for (TbOrder tbOrder : orderList) {
            tbOrder.setUpdateTime(new Date());
            tbOrder.setStatus("2");
            tbOrder.setPaymentTime(new Date());
            tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
        }
        return 1;
    }

    @Override
    public PageInfo<TbOrder> listOrderByUser(Integer pageNum, Integer pageSize, TbUser user) {
        PageHelper.startPage(pageNum, pageSize);
        List<TbOrder> tbOrderList = tbOrderMapper.listOrderByUser(user.getUsername());
        for (TbOrder tbOrder : tbOrderList) {
            String nickName = sellerService.getNikeNameBySellerId(tbOrder.getSellerId());
            tbOrder.setNickName(nickName);
            List<TbOrderItem> orderItems = tbOrderItemMapper.listOrderItemByOrderId(tbOrder.getOrderId());
            tbOrder.setOrderItems(orderItems);
        }

        PageInfo<TbOrder> pageInfo = new PageInfo<>(tbOrderList);
        return pageInfo;
    }

    @Override
    public void deleteItemOrderById(long id, String refund_amount) {
        // 查询对应的order_item
        TbOrderItem tbOrderItem = tbOrderItemMapper.selectByPrimaryKey(id);
        // 根据order_item对应的orderid查询对对应的order
        TbOrder tbOrder = tbOrderMapper.selectByPrimaryKey(tbOrderItem.getOrderId());
        // 修改order的相关数据
        tbOrder.setUpdateTime(new Date()); // 订单修改时间
        // 实际付款金额
        tbOrder.setPayment(new BigDecimal(tbOrder.getPayment().doubleValue() - Double.parseDouble(refund_amount)));
        tbOrder.setStatus("0");

        // 修改order
        tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
        // 删除order_item
//        tbOrderItemMapper.deleteByPrimaryKey(tbOrderItem.getId());
    }

}
